package com.hevs.samplewebapp.server.dao;

import java.util.List;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import com.hevs.samplewebapp.server.entities.InternalMessage;
import com.hevs.samplewebapp.server.entities.User;

/**
 * Implementation of the Interface InternalMessageDAO
 * 
 * @author Arnaud Durand
 * @date 23.04.2012
 * 
 */
public class InternalMessageDAOImpl implements InternalMessageDAO {

	@SuppressWarnings("unchecked")
	@Override
	/**
	 * Method to retrieve all the message from the server
	 */
	public List<InternalMessage> getAll(User local) {

		// Connection to the entity manager
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(User.class);
		query.setFilter("receiverUser == userKeyParam");
		query.declareParameters("String userKeyParam");
		try {
			List<InternalMessage> results = (List<InternalMessage>) query
					.execute(local.getKey());

			return (List<InternalMessage>) pm.detachCopyAll(results);
		} finally {
			pm.close();
		}

	}

	@Override
	/**
	 * Method to send an internal message to someone
	 */
	public void send(User local, User remote, InternalMessage mail) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			mail.setSenderUser(local.getKey());
			mail.setReceiverUser(remote.getKey());
			pm.makePersistent(mail);

		} finally {
			pm.close();
		}

	}

	@Override
	/**
	 * Method to delete an internal message
	 */
	public void remove(InternalMessage mail) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			InternalMessage m = pm.getObjectById(InternalMessage.class,
					mail.getKey());
			pm.deletePersistent(m);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pm.close();
		}

	}

}
